﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Xstream.Core;

namespace FlyingAPI
{
    public enum FlyingPigSTATUS
    {
        UPLOAD_OK, UPLOAD_FAILED, PAGEID_IS_WRONG, IMAGE_EXISTED, SERVER_INNER_FAILED,
        PAGE_FINISHED_EXISTED,
        DOWNLOAD_OK, DOWNLOAD_FAILED,
        REQUEST_OK, REQUEST_REJECT,
        REQUEST_TIMEOUT, REQUEST_DELAYED,
        TRANSACTION_SUCCESS,
        TRANSACTION_FAILED
    }

    public class FlyingPig
    {
        String conn;

        public int setConnect(string url)
        {
            conn = url;
            return 1;
        }

        public SearchJob requestSearchJob()
        {
            String searchJob_conn = conn + "RequestSearchJob";

            WebRequest request = WebRequest.Create(new Uri(searchJob_conn));
            request.Timeout = 15000;

            try
            {
                //接收服务器应答
                WebResponse response = request.GetResponse();

                //将应答转换为流形式
                Stream reader = response.GetResponseStream();

                StreamReader sr = new StreamReader(reader);
                string sXml = sr.ReadToEnd();
                sr.Close();

                if ((!sXml.Trim().Equals("null")) && (!sXml.Trim().Equals(String.Empty)))
                {
                    // XML反序列化
                    XStream ox = new XStream();
                    ox.Alias("SearchJob", typeof(SearchJob));
                    SearchJob sj = (SearchJob)ox.FromXml(sXml);

                    reader.Close();
                    return sj;
                }
                else
                {
                    reader.Close();
                    return null;
                }
            }
            catch (WebException ex)
            {
                return null;
            }
        }

        public List<SearchJob> requestSearchJobs(int maxSearchJobsNum)
        {
            String searchJobs_conn = conn + "RequestSearchJobs?maxJobs="+maxSearchJobsNum;

            WebRequest request = WebRequest.Create(new Uri(searchJobs_conn));
            request.Timeout = 15000;

            try
            {
                //接收服务器应答
                WebResponse response = request.GetResponse();

                //将应答转换为流形式
                Stream reader = response.GetResponseStream();

                StreamReader sr = new StreamReader(reader);
                string sXml = sr.ReadToEnd();
                sr.Close();

                if ((!sXml.Trim().Equals("null")) && (!sXml.Trim().Equals(String.Empty)))
                {
                    string[] sj_Xmls = sXml.Split(new string[] { "<Seperator/>" }, StringSplitOptions.RemoveEmptyEntries);

                    //XML反序列化
                    XStream ox = new XStream();
                    ox.Alias("SearchJob", typeof(SearchJob));
                    List<SearchJob> searchJobs = new List<SearchJob>();

                    foreach (string sj in sj_Xmls)
                    {
                        SearchJob searchJob = (SearchJob)ox.FromXml(sj);
                        searchJobs.Add(searchJob);
                    }

                    reader.Close();
                    return searchJobs;
                }
                else
                {
                    reader.Close();
                    return null;
                }

            }
            catch (WebException ex)
            {
                return null;
            }
        }

        public JobPage requestJobPage(int searchJobID)
        {
            String jobPage_conn = conn + "RequestJobPage?searchJobID=" + searchJobID;


            WebRequest request = WebRequest.Create(new Uri(jobPage_conn));
            request.Timeout = 150000;
            string sXml = string.Empty;
            WebResponse response = null;

            int count = 0;
            while (true)
            {
                try
                {
                    //接收服务器应答
                    //TODO 这地方会出错
                    response = request.GetResponse();
                    break;
                }
                catch (Exception e)
                {
                    System.Threading.Thread.Sleep(600000);
                    count++;
                    if (count > 5)
                    {
                        throw e;
                    }
                }
            }

            //将应答转换为流形式
            Stream reader = response.GetResponseStream();

            StreamReader sr = new StreamReader(reader);
            sXml = sr.ReadToEnd();
            sr.Close();
            reader.Close();

            if ((!sXml.Contains("status: no jobPage available")) && (!sXml.Trim().Equals(String.Empty)))
            {
                //XML反序列化
                XStream ox = new XStream();
                ox.Alias("JobPage", typeof(JobPage));
                JobPage jp = (JobPage)ox.FromXml(sXml);
                return jp;
            }
            else
            {
                return null;
            }
            /*catch (Exception other)
            {
                throw other;
            }*/
        }

        public FlyingPigSTATUS uploadImageInfo(ImageInfo imageInfo)
        {
            String uploadImageInfo_conn = conn + "UploadImageInfo";

            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("pageID", imageInfo.PageId.ToString());
            PostVars.Add("concept", imageInfo.Concept);
            PostVars.Add("tags", imageInfo.Tags);
            PostVars.Add("url", imageInfo.Url);
            PostVars.Add("relatedPage", imageInfo.RelatedPage);
            PostVars.Add("author", imageInfo.Author);
            PostVars.Add("sourcePhotoID", imageInfo.SourcePhotoId);
            

            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(uploadImageInfo_conn, "POST", PostVars);

                //获取返回信息
                string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo).Trim();
                
                return analyzeStatus(sRemoteInfo);
            }
            catch (Exception e)
            {
                return FlyingPigSTATUS.UPLOAD_FAILED;
            }
        }

        public int uploadImageInfos(List<ImageInfo> imageInfos)
        {
            String uploadImageInfo_conn = conn + "UploadImageInfos";

            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();

            XStream ox = new XStream();
            ox.Alias("ImageInfo", typeof(ImageInfo));

            String xmls = String.Empty;
            foreach (ImageInfo ii in imageInfos)
            {
                xmls += ox.ToXml(ii);
                xmls += "<Seperator/>";
            }

            PostVars.Add("xmls", xmls);
            int count = 0;
            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(uploadImageInfo_conn, "POST", PostVars);

                //获取返回信息
                string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo).Trim();

                int successNum = Convert.ToInt32(sRemoteInfo);
                return successNum;
            }
            catch (Exception e)
            {
                return -1;
            }
        }

        public FlyingPigSTATUS finishJobPage(int pageID)
        {
            String finishJobPage_conn = conn + "FinishJobPage?pageID="+pageID;
            WebRequest request = WebRequest.Create(new Uri(finishJobPage_conn));
            request.Timeout = 15000;

            WebResponse response = null;
            try
            {
                //接收服务器应答
                response = request.GetResponse();

                //将应答转换为流形式
                Stream reader = response.GetResponseStream();

                StreamReader sr = new StreamReader(reader);
                String sRemoteInfo = sr.ReadToEnd();
                sr.Close();

                return analyzeStatus(sRemoteInfo);

            }
            catch (Exception ex)
            {
                String a = response.ToString();
                throw ex;
            }
        }

        private FlyingPigSTATUS analyzeStatus(string remoteInfo)
        {
            switch (remoteInfo)
            {
                case "status: upload success":
                    return FlyingPigSTATUS.UPLOAD_OK;
                case "status: upload failed":
                    return FlyingPigSTATUS.UPLOAD_FAILED;
                case "status: imageInfo exsited":
                    return FlyingPigSTATUS.IMAGE_EXISTED;
                case "status: pageID is wrong":
                    return FlyingPigSTATUS.PAGEID_IS_WRONG;
                case "status: page is already finished":
                    return FlyingPigSTATUS.PAGE_FINISHED_EXISTED;
                case "status: transaction success":
                    return FlyingPigSTATUS.TRANSACTION_SUCCESS;
                case "status: transaction error":
                    return FlyingPigSTATUS.TRANSACTION_FAILED;
                default:
                    return FlyingPigSTATUS.SERVER_INNER_FAILED;
            }
        }

        public List<ImageInfo> requestImagesInfos(int maxImageInfosNum,String concept)
        {
            String imageLinks_conn = conn + "RequestImageInfos?maxImageInfos=" + maxImageInfosNum + "&concept=" + concept;
            WebRequest request = WebRequest.Create(new Uri(imageLinks_conn));
            request.Timeout = 15000;

            try
            {
                //接收服务器应答
                WebResponse response = request.GetResponse();

                //将应答转换为流形式
                Stream reader = response.GetResponseStream();

                StreamReader sr = new StreamReader(reader);
                string sXml = sr.ReadToEnd();
                sr.Close();

                if ((!sXml.Trim().Equals("null")) && (!sXml.Trim().Equals(String.Empty)))
                {
                    string[] ii_Xmls = sXml.Split(new string[] { "<Seperator/>" }, StringSplitOptions.RemoveEmptyEntries);

                    //XML反序列化
                    XStream ox = new XStream();
                    ox.Alias("ImageInfo", typeof(ImageInfo));
                    List<ImageInfo> imageInfos = new List<ImageInfo>();

                    foreach (string ii in ii_Xmls)
                    {
                        ImageInfo imageInfo = (ImageInfo)ox.FromXml(ii);
                        imageInfos.Add(imageInfo);
                    }

                    reader.Close();
                    return imageInfos;
                }
                else
                {
                    reader.Close();
                    return null;
                }
            }
            catch (WebException ex)
            {
                return null;
            }
        }

        public FlyingPigSTATUS uplodeImage(ImageInfo imageInfo,String imageFilePath)
        {
            String uploadImageFile_conn = conn + "UploadImageFile";
            System.Net.WebClient WebClientObj = new System.Net.WebClient();

            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadFile(uploadImageFile_conn, "POST", imageFilePath);
                //获取返回信息
                string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo).Trim();
                if (!sRemoteInfo.Equals("failed"))
                {
                    imageInfo.CachedUrl = sRemoteInfo;//写入返回地址

                    String uploadImage_conn = conn + "UploadImage";

                    System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
                    PostVars.Add("imageId", imageInfo.ImageId.ToString());
                    PostVars.Add("cachedUrl", imageInfo.CachedUrl);

                    try
                    {
                        byRemoteInfo = WebClientObj.UploadValues(uploadImage_conn, "POST", PostVars);

                        //获取返回信息
                        sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo).Trim();

                        return analyzeStatus(sRemoteInfo);
                    }
                    catch (Exception e)
                    {
                        return FlyingPigSTATUS.UPLOAD_FAILED;
                    }
                    return FlyingPigSTATUS.UPLOAD_OK;
                }
                else
                {
                    return FlyingPigSTATUS.UPLOAD_FAILED;
                }
            }
            catch (Exception e)
            {
                return FlyingPigSTATUS.UPLOAD_FAILED;
            }

        }
    }
}
